package com.repairsystem.repairsys.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.repairsystem.repairsys.common.Const;
import com.repairsystem.repairsys.common.ResponseCode;
import com.repairsystem.repairsys.common.ServerResponse;
import com.repairsystem.repairsys.dao.*;
import com.repairsystem.repairsys.pojo.*;
import com.repairsystem.repairsys.service.IUserService;
import com.repairsystem.repairsys.vo.FaultByUserVo;
import com.repairsystem.repairsys.vo.FaultVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service("iUserService")
@Transactional
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private FaultMapper faultMapper;
    @Autowired
    private FaultCategoryMapper faultCategoryMapper;
    @Autowired
    private MaintainerMapper maintainerMapper;
    @Autowired
    private CommentMapper commentMapper;

    @Override
    public ServerResponse<User> login(String userNum, String userPassword) {
        ServerResponse<String> validResponse = this.checkValid(userNum, Const.NUM);
        if(validResponse.isSuccess()){
            return ServerResponse.createByErrorMassage("用户名不存在！！！");
        }
        User user = userMapper.selectLogin(userNum, userPassword);
        if(user == null){
            return ServerResponse.createByErrorMassage("密码错误！！！");
        }
        user.setUserPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess("登录成功！",user);
    }

    public ServerResponse<String> checkValid(String str,String type){
        if(StringUtils.isNotBlank(type)){
            if(Const.NUM.equals(type)){
                int resultCount = userMapper.checkUsernum(str);
                if(resultCount > 0){
                    return ServerResponse.createByErrorMassage("用户名已存在");
                }
            }
            if(Const.TEL.equals(type)){
                int resultCount = userMapper.checkTel(str);
                if(resultCount > 0){
                    return ServerResponse.createByErrorMassage("电话已存在");
                }
            }
        }else{
            return ServerResponse.createByErrorMassage("参数错误");
        }
        return ServerResponse.createBySuccessMassage("校验成功");
    }

    @Override
    public ServerResponse<PageInfo> list(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Fault> faultList = faultMapper.selectAllFault();
        if(faultList.size() == 0 || faultList == null){
            return ServerResponse.createByErrorMassage("还没有任何故障报修");
        }
        List<FaultCategory> faultCategoryList = faultCategoryMapper.selectAllFaultCategory();
        List<Maintainer> maintainerList = maintainerMapper.selectAllMaintainIdAndName();
        List<FaultVo> faultVoList = Lists.newArrayList();
        for (Fault fault:faultList) {
            FaultVo faultVo = createFaultVo(fault,faultCategoryList,maintainerList);
            faultVoList.add(faultVo);
        }

        PageInfo pageInfo = new PageInfo(faultList);
        pageInfo.setList(faultVoList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    private FaultVo createFaultVo(Fault fault, List<FaultCategory> faultCategoryList,List<Maintainer> maintainerList) {
        FaultVo faultVo = new FaultVo();
        faultVo.setFaultId(fault.getFaultId());
        faultVo.setFaultDescribe(fault.getFaultDescribe());
        faultVo.setFaultCategoryId(fault.getFaultCategoryId());
        faultVo.setFaultSite(fault.getFaultSite());
        faultVo.setFaultSolution(fault.getFaultSolution());
        faultVo.setFaultWay(fault.getFaultWay());
        faultVo.setFaultTime(fault.getFaultTime());
        faultVo.setFaultSolutionTime(fault.getFaultSolutionTime());
        faultVo.setFaultMaintainerId(fault.getFaultMaintainerId());
        faultVo.setFaultStatus(fault.getFaultStatus());
        for (FaultCategory faultCategory:faultCategoryList) {
            if(fault.getFaultCategoryId() == faultCategory.getFaultCategoryId()){
                faultVo.setFaultCategoryName(faultCategory.getFaultCategoryName());
            }
        }
        for (Maintainer maintainer:maintainerList) {
            if(fault.getFaultMaintainerId() == maintainer.getMaintainerId()){
                faultVo.setMaintainerName(maintainer.getMaintainerName());
            }
        }
        return faultVo;
    }

    @Override
    public ServerResponse<PageInfo> selectFaultByCategory(Integer pageNum, Integer pageSize, String faultCategoryId) {
        PageHelper.startPage(pageNum,pageSize);
        List<Fault> faultList = faultMapper.selectByFaultCategoryId(Long.parseLong(faultCategoryId));
        if(faultList.size() == 0 || faultList == null){
            return ServerResponse.createByErrorMassage("没有当前类型的故障报修");
        }
        List<FaultCategory> faultCategoryList = faultCategoryMapper.selectAllFaultCategory();
        List<Maintainer> maintainerList = maintainerMapper.selectAllMaintainIdAndName();
        List<FaultVo> faultVoList = Lists.newArrayList();
        for (Fault fault:faultList) {
            FaultVo faultVo = createFaultVo(fault,faultCategoryList,maintainerList);
            faultVoList.add(faultVo);
        }
        PageInfo pageInfo = new PageInfo(faultList);
        pageInfo.setList(faultVoList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse selectAllFaultCategory() {
        List<FaultCategory> faultCategoryList = faultCategoryMapper.selectAllFaultCategory();
        if(faultCategoryList == null){
            return ServerResponse.createByErrorMassage("没有任何故障类型");
        }
        return ServerResponse.createBySuccess(faultCategoryList);
    }

    @Override
    public ServerResponse userPlaceOrder(Fault fault) {
        if(fault == null){
            return ServerResponse.createByErrorCodeMassage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),"参数错误");
        }
        byte status = 0;
        fault.setFaultStatus(status);
        int resultCount = faultMapper.insertSelective(fault);
        if(resultCount > 0){
            return ServerResponse.createBySuccessMassage("添加成功");
        }
        return ServerResponse.createByErrorMassage("添加失败");
    }

    @Override
    public ServerResponse<PageInfo> selectFaultByUserId(Integer pageNum, Integer pageSize, String userId) {
        if(userId == null){
            return ServerResponse.createByErrorCodeMassage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),"参数错误");
        }
        PageHelper.startPage(pageNum,pageSize);
        List<Fault> faultList = faultMapper.selectFaultByUserId(userId);
        if(faultList.size() == 0 || faultList == null){
            return ServerResponse.createByErrorMassage("还没有下单呢！");
        }
        List<FaultCategory> faultCategoryList = faultCategoryMapper.selectAllFaultCategory();
        List<FaultByUserVo> faultByUserVoList = Lists.newArrayList();
        for (Fault fault:faultList) {
            FaultByUserVo faultByUserVo = createFaultByUserVo(fault,faultCategoryList);
            faultByUserVoList.add(faultByUserVo);
        }
        PageInfo pageInfo = new PageInfo(faultList);
        pageInfo.setList(faultByUserVoList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    @Override
    public ServerResponse newPassword(String userId,String oldPassword, String newPassword, String newPasswordAgain) {
       if (!StringUtils.isNotBlank(oldPassword)){
           return ServerResponse.createByErrorCodeMassage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),"参数错误");
       }
       String password = userMapper.selectPassword(userId);
       if(!password.equals(oldPassword)){
           return ServerResponse.createByErrorMassage("原密码错误");
       }
       if(!newPassword.equals(newPasswordAgain)){
           return ServerResponse.createByErrorMassage("新密码两次输入不一致");
       }
       if(newPassword.length() < 4){
           return ServerResponse.createByErrorMassage("密码长度不能小于4");
       }
       User user = userMapper.selectByPrimaryKey(Long.parseLong(userId));

       user.setUserPassword(newPassword);

        int resultCount = userMapper.updateByPrimaryKeySelective(user);

        if(resultCount > 0){
            return ServerResponse.createBySuccess("修改成功");
        }
        return ServerResponse.createByErrorMassage("修改失败");
    }

    @Override
    public ServerResponse userComment(String commentText, String faultId, String maintainerId) {
        if (!StringUtils.isNotBlank(faultId) || !StringUtils.isNotBlank(maintainerId)){
            return ServerResponse.createByErrorCodeMassage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),"参数错误");
        }
        int resultCount1 = faultMapper.checkFaultStatus(faultId, "3");
        if(resultCount1 <= 0){
            return ServerResponse.createByErrorMassage("参数异常");
        }
        int resultCount2 = faultMapper.checkFaultWithMaintainerId(faultId,maintainerId);
        if(resultCount2 <= 0){
            return ServerResponse.createByErrorMassage("参数异常");
        }
        Comment comment = new Comment();
        comment.setCommentDate(new Date());
        comment.setCommentText(commentText);
        comment.setFaultId(Long.parseLong(faultId));
        comment.setMaintainerId(Long.parseLong(maintainerId));
        int resultCount3 = commentMapper.insertSelective(comment);
        Fault fault = faultMapper.selectByPrimaryKey(Long.parseLong(faultId));
        byte status = 4;
        fault.setFaultStatus(status);
        int resultCount4 = faultMapper.updateByPrimaryKeySelective(fault);
        if(resultCount3 > 0 && resultCount4 > 0){

            return ServerResponse.createBySuccessMassage("评价成功");
        }
        return ServerResponse.createByErrorMassage("评价失败");
    }

    private FaultByUserVo createFaultByUserVo(Fault fault, List<FaultCategory> faultCategoryList) {
        FaultByUserVo faultByUserVo = new FaultByUserVo();
        faultByUserVo.setFaultId(fault.getFaultId());
        faultByUserVo.setFaultDescribe(fault.getFaultDescribe());
        faultByUserVo.setFaultSite(fault.getFaultSite());
        faultByUserVo.setFaultCategoryId(fault.getFaultCategoryId());
        faultByUserVo.setFaultMaintainerId(fault.getFaultMaintainerId());
        for (FaultCategory faultCategory:faultCategoryList) {
            if(fault.getFaultCategoryId() == faultCategory.getFaultCategoryId()){
                faultByUserVo.setFaultCategoryName(faultCategory.getFaultCategoryName());
            }
        }
        faultByUserVo.setFaultStatus(fault.getFaultStatus());
        switch (fault.getFaultStatus()){
            case 0:faultByUserVo.setFaultStatusName("已发送至管理员");break;
            case 1:faultByUserVo.setFaultStatusName("管理员已派单");break;
            case 2:faultByUserVo.setFaultStatusName("维修员已接单");break;
            case 3:faultByUserVo.setFaultStatusName("已完成，待评价");break;
            default:break;
        }
        return faultByUserVo;
    }

}
